package ThreadTest;

/**
 * wait()  执行线程则会进入阻塞
 * notify()     唤醒一个线程
 * notifyAll()   唤醒多个线程
 * 说明：
 * 1.wait(),notify(),notifyAll()三个方法必须使用在同步代码块中或同步方法中
 * 2.wait(),notify(),notifyAll()三个方法的调用者必须是同步代码块或同步方法中的同步监视器
 *     否则，会出现IllegalMonitorStateException异常
 *3.wait(),notify(),notifyAll()三个方法定义在Object类中
 *
 */
//两个线程交互执行
public class CommunicationTest implements Runnable {
    private  int m = 1;
    @Override
    public void run() {
            while (true) {
                synchronized (this) {
                    notify();
                if (m <=100) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + m);
                    m++;
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            }
        }
    }
}

class CommTest{
    public static void main(String[] args) {

        CommunicationTest thread = new CommunicationTest();
        Thread thread1 = new Thread(thread);
        Thread thread2 = new Thread(thread);


        thread1.setName("线程一：");
        thread2.setName("线城二：");

        thread1.start();
        thread2.start();
    }

}